<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useI18n } from "@/hooks/web/useI18n";
import { loginApi, getUserInfoApi } from "@/apis/login";
import { useAppStore } from "@/store/modules/app";
import { usePermissionStore } from "@/store/modules/permission";
import { useUserStore } from "@/store/modules/user";
import { useRouter } from "vue-router";
import Icon from "@/components/common/icon";

const appStore = useAppStore();
const userStore = useUserStore();
const permissionStore = usePermissionStore();
const { currentRoute, addRoute, push, getRoutes } = useRouter();
const { t } = useI18n();

const form = reactive({
  account: "",
  password: "",
  remember: userStore.getRememberMe,
});

const rules = {
  account: [
    {
      required: true,
      message: t("login.username") + " " + t("common.required"),
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: t("login.password") + " " + t("common.required"),
      trigger: "blur",
    },
  ],
};

const loading = ref(false);
const redirect = ref("");

watch(
  () => currentRoute.value,
  (route) => {
    redirect.value = route?.query?.redirect || "";
  },
  { immediate: true }
);

onMounted(() => {
  // 初始化登录信息
  const loginInfo = userStore.getLoginInfo;
  if (loginInfo) {
    form.account = loginInfo.account;
    form.password = loginInfo.password;
  }
});
const router = useRouter();
// 获取角色信息
const getUserInfo = async () => {
  const params = {};
  const res = await getUserInfoApi(params);
  if (res) {
    const routers = res.data.routers || [];
    userStore.setRoleRouters(routers);
    userStore.setUserInfo(res.data.user);

    await permissionStore.generateRoutes("server", routers).catch(() => {});
    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route); // 动态添加可访问路由表
    });
    permissionStore.setIsAddRouters(true);
    push({ path: redirect.value || "/" });
  }
};
// 登录逻辑
const signIn = () => {
  const loginForm = formRef.value;
  loginForm.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      const res = await loginApi({
        account: form.account,
        password: form.password,
      });
      if (res) {
        if (form.remember) {
          userStore.setLoginInfo({
            account: form.account,
            password: form.password,
          });
        } else {
          userStore.setLoginInfo(undefined);
        }
        userStore.setRememberMe(form.remember);
        // userStore.setUserInfo(res.data)
        userStore.setToken(`Bearer ${res.data.token}`);
        //动态路由
        if (appStore.getDynamicRouter) {
          await getUserInfo();
        } else {
          await permissionStore.generateRoutes("static").catch(() => {});
          permissionStore.getAddRouters.forEach((route) => {
            router.addRoute(route);
          });
          permissionStore.setIsAddRouters(true);
          //跳转第一个路由菜单
          router.push({
            path: redirect.value || permissionStore.addRouters[0].path,
          });
        }
      }
    } finally {
      loading.value = false;
    }
  });
};

const toRegister = () => {
  emit("to-register");
};

const formRef = ref(null);

const hoverColor = "var(--el-color-primary)";
</script>

<template>
  <el-form
    :model="form"
    :rules="rules"
    ref="formRef"
    label-position="top"
    size="large"
    class="login-form p-40px">
    <div class="w-100% flex justify-center items-center mb-20px">
      <img src="@/assets/imgs/text_logo.png" style="width: 100%" alt="" />
    </div>
    <el-form-item prop="account" label="账号">
      <el-input
        v-model="form.account"
        placeholder="请输入账号"
        autocomplete="username" />
    </el-form-item>

    <el-form-item prop="password" label="密码">
      <el-input
        type="password"
        v-model="form.password"
        placeholder="请输入登录密码"
        autocomplete="current-password"
        @keydown.enter.prevent="signIn" />
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        :loading="loading"
        class="w-full"
        @click="signIn">
        {{ t("login.login") }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.login-form {
  margin: 0 auto;
  position: relative;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.cursor-pointer {
  cursor: pointer;
}

.ant-icon {
  transition: color 0.3s;
}

.ant-icon:hover {
  color: var(--el-color-primary);
}
</style>
